//
//  BN_PersonalInfoModifyViewController.m
//  BabyNow
//
//  Created by 刘泽琛 on 14-5-19.
//  Copyright (c) 2014年 iMobile. All rights reserved.
//

#import "BN_PersonalInfoModifyViewController.h"
#define PATH_DOC_USERDATA [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"UserData"]

@interface BN_PersonalInfoModifyViewController () {
    NSArray *parentFields;
    NSArray *teacherFields;
    NSArray *useFields;
    
    BN_TakePhotoController *takePhotoVCtrl_;
    MLImageCrop *imageCrop_;
    ZYQAssetPickerController *picker_;
    BN_MyInfoHelper *myInfoHelper_;
    MJRefreshHeaderView *_header;
}
@end

@implementation BN_PersonalInfoModifyViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // UI+64
    if (IOS7) {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.navigationController.navigationBarHidden = NO;
    self.tabBarController.tabBar.hidden = NO;
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewDidDisappear:(BOOL)animated {
    takePhotoVCtrl_ = nil;
    [[NSNotificationCenter defaultCenter]postNotificationName:@"KTEXTINFO_HIDEKEYBOARD" object:nil];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 风火轮
    [self viewLoadHintView];
    
    self.view.backgroundColor = APP_OBJECT_GRAY_COLOR;
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(toSaveInfoAction)];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"houtui"] style:UIBarButtonItemStylePlain target:self action:@selector(backRootVC)];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    self.title = @"个人资料设置";
    parentFields = @[@"头像",@"账号",@"昵称",@"宝宝生日",@"电话号码"];
    teacherFields = @[@"头像",@"账号",@"昵称",@"毕业院校",@"学历",@"电话号码",@"教育格言"];
        
    userInfo = [BN_UserHelper unArchiverAccountInfo];
    self.userType = [userInfo.userType integerValue];
    switch (self.userType) {
        case ENUM_ROLE_LEADER:
            useFields = teacherFields;
            break;
        case ENUM_ROLE_CLASS_TEACHER:
            useFields = teacherFields;
            break;
        case ENUM_ROLE_PARENT:
            useFields = parentFields;
            break;
        default:
            break;
    }
    
    // 生日拾取器 dataPicker
    self.birthdayPicker = [[UIDatePicker alloc]init];
    switch (MAIN_VERSION) {
        case 6:
            self.birthdayPicker.frame = CGRectMake(0, SCREEN_HEIGHT-162-44, SCREEN_WIDTH, 162);
            break;

        default:
            self.birthdayPicker.frame = CGRectMake(0, FULLSCREEN_HEIGHT-162, SCREEN_WIDTH, 162);

            break;
    }
    [self.birthdayPicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
    self.birthdayPicker.datePickerMode = UIDatePickerModeDate;
    [self.view addSubview:self.birthdayPicker];
    self.birthdayPicker.hidden = YES;
    
    // 列表
    self.modifyTableView.scrollEnabled = YES;
    switch (MAIN_VERSION) {
        case 6:
            self.modifyTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-44);
            break;
        default:
            self.modifyTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, FULLSCREEN_HEIGHT);
            self.modifyTableView.backgroundColor = APP_OBJECT_GRAY_COLOR;
            self.modifyTableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
            self.modifyTableView.scrollIndicatorInsets = UIEdgeInsetsMake(64, 0, 0, 0);
            break;
    }
    [self setExtraCellLineHidden:self.modifyTableView];
    _modifyTableView.backgroundColor = APP_OBJECT_GRAY_COLOR;
    if ([self.modifyTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.modifyTableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    // 下拉刷新
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = self.modifyTableView;
    header.delegate = self;
    _header = header;
    
    // 检查键盘
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeTableViewFrame:) name:@"KMINE_CHANGE_PERSONAL_TABLEVIEW_HEIGHT" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(tableviewFrameRecovery:) name:@"K_MINE_TABLEVIEW_FRAME_RECOVERY" object:nil];
    
    // helper
    myInfoHelper_ = [[BN_MyInfoHelper alloc]init];
    [self performSelectorInBackground:@selector(requestNetData) withObject:nil];
}

#pragma mark
#pragma mark 生命周期

- (void)releaseResource {
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"KTEXTINFO_HIDEKEYBOARD" object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"K_MINE_PERSON_SETTING_DOWN_KEYBOARD" object:nil];
    
    imageCrop_.delegate = nil;
    imageCrop_ = nil;
    
    picker_.delegate = nil;
    picker_ = nil;
    
    _header.delegate = nil;
    [_header free];
    _header = nil;
    
    self.modifyTableView.delegate = nil;
    self.modifyTableView.dataSource = nil;
    self.modifyTableView = nil;
    
    [myInfoHelper_ cancleQueryEvalList];
    myInfoHelper_ = nil;
    
    BN_PersonModifyModel *personModel = [BN_PersonModifyModel sharedModifyModel];
    personModel.nickName = nil;
    personModel.biyeSchoolName = nil;
    personModel.xueLiName = nil;
    personModel.telPName = nil;
    personModel.signName = nil;
    personModel.babyBirtName = nil;
    
}

- (void)backRootVC {
    [self releaseResource];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma makr
#pragma mark - 刷新控件的代理方法

- (void)upLoadFinished:(MJRefreshBaseView *)refreshView {
    // 列表开始加载，开始数据请求
    // [self loadNextNetData];
    
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    // 列表开始刷新，开始数据请求
    [self requestNetData];
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    switch ([refreshView viewType]) {
        case -1:
            [self performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:0.85];
            break;
        case 1:
            [self performSelector:@selector(upLoadFinished:) withObject:refreshView afterDelay:0];
            break;
        default:
            break;
    }
}

- (void)refreshViewEndRefreshing:(MJRefreshBaseView *)refreshView
{
}

- (void)refreshView:(MJRefreshBaseView *)refreshView stateChange:(MJRefreshState)state
{
    switch (state) {
        case MJRefreshStateNormal:
            break;
        case MJRefreshStatePulling:
            break;
            
        case MJRefreshStateRefreshing:
            break;
        default:
            break;
    }
}

#pragma mark TableView delegate

-(void)setExtraCellLineHidden:(UITableView *)tableView
{
    UIView *view = [UIView new];
    view.backgroundColor = APP_OBJECT_GRAY_COLOR;
    [tableView setTableFooterView:view];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc]init];
    view.backgroundColor = APP_OBJECT_GRAY_COLOR;
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 20;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0 && indexPath.section == 0) {
        return 64;
    }else
    {
        return 44;
    }
    return 0;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger sectionCount = 0;
    
    if (section == 0) {
        sectionCount = 1;
    }
    if (section == 1) {
        sectionCount = useFields.count-1;
    }
    return sectionCount;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger row = indexPath.row;
    NSInteger section = indexPath.section;
    
    if (row == 0 && section ==0) {
        static NSString *identifier = @"BN_PersonalModifyHeadPhoto";
        BOOL nibsRegrNib = NO;
        if (!nibsRegrNib) {
            UINib *nib = [UINib nibWithNibName:NSStringFromClass([BN_PersonalModifyHeadPhoto class]) bundle:nil];
            [tableView registerNib:nib forCellReuseIdentifier:identifier];
            nibsRegrNib = YES;
        }
        BN_PersonalModifyHeadPhoto *cell = (BN_PersonalModifyHeadPhoto*)[tableView dequeueReusableCellWithIdentifier:identifier];
        // modify by lzc 取到本地用户头像图片
        if (self.userPhotoImage) {
            cell.userPhotoImageView.image = self.userPhotoImage;
        }else {
            NSString *path = [NSString stringWithFormat:@"%@/userPhoto.png",PATH_DOC_USERDATA];
            NSFileManager *fileManager = [NSFileManager defaultManager];
            if ([fileManager fileExistsAtPath:path]) {
                UIImage *userPhotoImage = [UIImage imageWithContentsOfFile:path];
                cell.userPhotoImageView.image = userPhotoImage;
            }else {
                NSString *headUrl = self.netDict[@"headUrl"];
                if (![headUrl isEqual:[NSNull null]] && self.netDict) {
                    headUrl = [THUMBNAIL_BASEURL stringByAppendingString:headUrl];
                    [cell.userPhotoImageView setImageWithURL:[NSURL URLWithString:headUrl]];
                }else {
                    cell.userPhotoImageView.image = [UIImage imageNamed:@"userPhoto"];
                }
            }
        }
        return cell;
    }else {
        static NSString *identifier = @"BN_PersonalModifyTextInfo";
        BOOL nibsRegrNib = NO;
        if (!nibsRegrNib) {
            UINib *nib = [UINib nibWithNibName:NSStringFromClass([BN_PersonalModifyTextInfo class]) bundle:nil];
            [tableView registerNib:nib forCellReuseIdentifier:identifier];
            nibsRegrNib = YES;
        }
        BN_PersonalModifyTextInfo *cell = (BN_PersonalModifyTextInfo*)[tableView dequeueReusableCellWithIdentifier:identifier];
        cell.tag = indexPath.row;
        BN_PersonModifyModel *personModel = [BN_PersonModifyModel sharedModifyModel];
        if (self.userType == ENUM_ROLE_CLASS_TEACHER || self.userType == ENUM_ROLE_LEADER) {
            if (indexPath.row == 0 && indexPath.section == 1) {
                cell.fieldsInfoTextField.enabled = NO;
                userInfo = [BN_UserHelper unArchiverAccountInfo];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.fieldsInfoTextField.text = [NSString stringWithFormat:@"%@",userInfo.account];
            }
            if (indexPath.row == 1 && indexPath.section == 1) {
                if (self.netDict) {
                    cell.fieldsInfoTextField.text = [NSString stringWithFormat:@"%@",personModel.nickName];
                }else {
                    cell.fieldsInfoTextField.text = @"未填写";
                }
                cell.fieldsInfoTextField.enabled = NO;
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
            }
            if (indexPath.row == 2 && indexPath.section == 1) {
                if (self.netDict) {
                    cell.fieldsInfoTextField.text = [NSString stringWithFormat:@"%@",personModel.biyeSchoolName];
                }else {
                    cell.fieldsInfoTextField.text = @"未填写";
                }
            }
            if (indexPath.row == 3 && indexPath.section == 1) {
                if (self.netDict) {
                    cell.fieldsInfoTextField.text = [NSString stringWithFormat:@"%@",personModel.xueLiName];
                }else {
                    cell.fieldsInfoTextField.text = @"未填写";
                }
            }
            if (indexPath.row == 4 && indexPath.section == 1) {
                if (self.netDict) {
                    cell.fieldsInfoTextField.text = [NSString stringWithFormat:@"%@",personModel.telPName];
                }else {
                    cell.fieldsInfoTextField.text = @"未填写";
                }
            }
            if (indexPath.row == 5 && indexPath.section == 1) {
                if (self.netDict) {
                    cell.fieldsInfoTextField.text = [NSString stringWithFormat:@"%@",personModel.signName];
                }else {
                    cell.fieldsInfoTextField.text = @"未填写";
                }
            }
        }
        
        if (self.userType == ENUM_ROLE_PARENT) {
 
            if (indexPath.row == 0 && indexPath.section == 1) {
                cell.fieldsInfoTextField.enabled = NO;
                userInfo = [BN_UserHelper unArchiverAccountInfo];
                cell.fieldsInfoTextField.text = [NSString stringWithFormat:@"%@",userInfo.account];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            
            if (indexPath.row == 1 && indexPath.section == 1) {
                if (self.netDict) {
                    cell.fieldsInfoTextField.text = [NSString stringWithFormat:@"%@",personModel.nickName];
                }else {
                    cell.fieldsInfoTextField.text = @"未填写";
                }
                cell.fieldsInfoTextField.enabled = NO;
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            if (indexPath.row == 2 && indexPath.section == 1) {
                if (self.netDict) {
                    NSString *dateStr = FORMAT_STR(personModel.babyBirtName);
                    if ([dateStr isEqualToString:@"未填写"]) {
                        cell.fieldsInfoTextField.text = dateStr;
                    }else {
                        NSRange rang = NSMakeRange(0, 10);
                        NSString *strRang = [dateStr substringWithRange:rang];
                        cell.fieldsInfoTextField.text = strRang;
                    }
                }else {
                    cell.fieldsInfoTextField.text = @"未填写";
                }
            }
            if (indexPath.row == 3 && indexPath.section == 1) {
                if (self.netDict) {
                    cell.fieldsInfoTextField.text = [NSString stringWithFormat:@"%@",personModel.telPName];
                }else {
                    cell.fieldsInfoTextField.text = @"未填写";
                }
            }
        }
        cell.fieldsName.text = useFields[indexPath.row+1];
        return cell;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0 && indexPath.section == 0) {
        [self takePhotoOrcameraAction];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"KTEXTINFO_HIDEKEYBOARD" object:nil];
    self.birthdayPicker.hidden = YES;
    self.modifyTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
}

#pragma mark
#pragma mark UIActionSheet
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        // 拍照
        __block BN_PersonalInfoModifyViewController *blockSelf = self;
        takePhotoVCtrl_ = [[BN_TakePhotoController alloc]init];
        [takePhotoVCtrl_ getTodealWith:^(UIImage *img) {
            CGSize size = CGSizeMake(300,300);
            UIImage *newImg = [UIImage createRoundedRectImage:img size:size radius:150];
            blockSelf.userPhotoImage = newImg;
            [blockSelf.modifyTableView reloadData];
        }];
        [self.navigationController presentViewController:takePhotoVCtrl_ animated:YES completion:nil];
    }else if (buttonIndex == 1) {
        // 相册选择
        [self openCameraAction];
        
    }else if(buttonIndex == 2) {
        // 取消
    }
}

#pragma mark 
#pragma mark 打开相册
- (void)openCameraAction {
    picker_ = [[ZYQAssetPickerController alloc] init];
    picker_.maximumNumberOfSelection = 2;
    picker_.assetsFilter = [ALAssetsFilter allPhotos];
    picker_.showEmptyGroups = NO;
    picker_.delegate = self;
    picker_.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        if ([[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo]) {
            NSTimeInterval duration = [[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
            return duration >= 5;
        } else {
            return YES;
        }
    }];
    [self presentViewController:picker_ animated:YES completion:NULL];
}

-(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets{
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // src.contentSize = CGSizeMake(assets.count*src.frame.size.width, src.frame.size.height);
        dispatch_async(dispatch_get_main_queue(), ^{
            // pageControl.numberOfPages = assets.count;
        });
        
        for (int i=0; i<assets.count; i++) {
            ALAsset *asset=assets[i];
            UIImage *tempImg = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
            // self.image = tempImg;
            dispatch_async(dispatch_get_main_queue(), ^{
                imageCrop_ = [[MLImageCrop alloc]init];
                imageCrop_.delegate = self;
                imageCrop_.ratioOfWidthAndHeight = 800.0f/600.0f;
                imageCrop_.image = tempImg;
                [imageCrop_ showWithAnimation:YES];
            });
        }
    });
}

#pragma mark - crop delegate
- (void)cropImage:(UIImage*)cropImage forOriginalImage:(UIImage*)originalImage
{
    CGSize size = CGSizeMake(300,300);
    UIImage *newImg = [UIImage createRoundedRectImage:cropImage size:size radius:150];
    self.userPhotoImage = newImg;
    [self.modifyTableView reloadData];
}

- (void)backBeforeVc {
    // code...
}

#pragma mark
#pragma mark Action

// 宝宝生日
- (void)dateChanged:(id)sender {
    
    // UI显示
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:1];
    BN_PersonalModifyTextInfo *cell = [self tableView:self.modifyTableView cellForRowAtIndexPath:indexPath];
    NSDate *selected = [self.birthdayPicker date];
    NSTimeZone *timeZone = [NSTimeZone timeZoneForSecondsFromGMT:3600*8];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeZone:timeZone];
    [formatter setDateFormat:@"YYYY-MM-dd"];
    NSString *dateString = [formatter stringFromDate:selected];
    NSLog(@"%@",dateString);
    cell.fieldsInfoTextField.text = dateString;

    // 重新加载TableView
    BN_PersonModifyModel *personModel = [BN_PersonModifyModel sharedModifyModel];
    personModel.babyBirtName = dateString;
    [self.modifyTableView reloadData];
}

// 列表原始高度
- (void)tableviewFrameRecovery:(NSNotification *)notification {
    switch (MAIN_VERSION) {
        case 6:
        {
            [UIView animateWithDuration:0.3 animations:^{

            self.modifyTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-44);
            } completion:^(BOOL finished) {
            }];
        }
            break;
        default:
            [UIView animateWithDuration:0.3 animations:^{
                self.modifyTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, FULLSCREEN_HEIGHT);
            } completion:^(BOOL finished) {
            }];
            break;
    }
}

// 是否照相或从相册中选择
- (void)takePhotoOrcameraAction {
    UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                  initWithTitle:nil
                                  delegate:self
                                  cancelButtonTitle:@"取消"
                                  destructiveButtonTitle:nil
                                  otherButtonTitles:@"拍照", @"从相册选择",nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
    [actionSheet showInView:self.view];
}

// 改变列表的高度
- (void)changeTableViewFrame:(NSNotification *)notification {
    if (notification.object) {
        NSInteger receiveInt = [notification.object integerValue];
        switch (receiveInt) {
            case 1:
            {
                [UIView animateWithDuration:0.3 animations:^{
                    self.birthdayPicker.hidden = YES;
                    self.modifyTableView.frame = CGRectMake(0, -(40+44+64), SCREEN_WIDTH, SCREEN_HEIGHT);
                } completion:^(BOOL finished) {
                }];
            }
                break;
            case 2:
            {
                [UIView animateWithDuration:0.3 animations:^{
                    self.modifyTableView.frame = CGRectMake(0, -(40+44+64), SCREEN_WIDTH, FULLSCREEN_HEIGHT);
                } completion:^(BOOL finished) {
                    // 如果是家长权限的话、时间选择器弹出
                    userInfo = [BN_UserHelper unArchiverAccountInfo];
                    NSInteger userType = [userInfo.userType integerValue];
                    switch (userType) {
                        case ENUM_ROLE_PARENT:
                        {
                            [[NSNotificationCenter defaultCenter]postNotificationName:@"K_MINE_PERSON_SETTING_DOWN_KEYBOARD" object:nil];
                            self.birthdayPicker.hidden = NO;
                        }
                            break;
                        default:
                            break;
                    }
                }];
                
            }
                break;
            case 3:
            {
                self.birthdayPicker.hidden = YES;
                [UIView animateWithDuration:0.3 animations:^{
                    self.modifyTableView.frame = CGRectMake(0, -(40+44+64), SCREEN_WIDTH, FULLSCREEN_HEIGHT);
                } completion:^(BOOL finished) {
                }];
            }
                break;
            case 4:
            {
                self.birthdayPicker.hidden = YES;
                [UIView animateWithDuration:0.3 animations:^{
                    self.modifyTableView.frame = CGRectMake(0, -(40+44*2+64), SCREEN_WIDTH, FULLSCREEN_HEIGHT);
                } completion:^(BOOL finished) {
                }];
            }
                break;
            case 5:
            {
                self.birthdayPicker.hidden = YES;
                [UIView animateWithDuration:0.3 animations:^{
                    self.modifyTableView.frame = CGRectMake(0, -(40+44*3+64), SCREEN_WIDTH, FULLSCREEN_HEIGHT);
                } completion:^(BOOL finished) {
                }];
            }
                break;
            default:
                break;
        }
    }
}

// 保存信息
- (void)toSaveInfoAction {
    
    // UI
    self.birthdayPicker.hidden = YES;
    [[NSNotificationCenter defaultCenter]postNotificationName:@"K_MINE_PERSON_SETTING_DOWN_KEYBOARD" object:nil];
    self.modifyTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    [SVProgressHUD showWithStatus:@"个人设置页准备更新" maskType:SVProgressHUDMaskTypeBlack];
    
    // 数据
    __block BN_PersonalInfoModifyViewController *blockSelf_ = self;
    BN_PersonModifyModel *personModifyModeal = [BN_PersonModifyModel sharedModifyModel];
    NSString *birthDate = personModifyModeal.babyBirtName;
    NSString *gradUniv  = personModifyModeal.biyeSchoolName;
    NSString *educ = personModifyModeal.xueLiName;
    NSString *sign = personModifyModeal.signName;
    NSString *phone = personModifyModeal.telPName;
    
    userInfo = [BN_UserHelper unArchiverAccountInfo];
    NSInteger userType = [userInfo.userType integerValue];
    switch (userType) {
        case ENUM_ROLE_CLASS_TEACHER:
            birthDate = @"1991-11-01";
            break;
        case ENUM_ROLE_LEADER:
            birthDate = @"1991-11-01";
            break;
        default:
            break;
    }
    
    // 封装1张图片
    NSString *fileName = @"babyNow.png";
    NSData *imgData = UIImagePNGRepresentation(self.userPhotoImage);
    
    if (imgData.length <= 0) {
        UIImage *defaultImg  = nil;
        NSString *localUserPhotoPath = [PATH_DOC_USERDATA stringByAppendingPathComponent:@"userPhoto.png"];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:localUserPhotoPath]) {
            defaultImg = [[UIImage alloc]initWithContentsOfFile:localUserPhotoPath];
        }else {
            defaultImg = [UIImage imageNamed:@"userPhoto"];
        }

        imgData = UIImagePNGRepresentation(defaultImg) ;
    }
    NSArray *fileInfoArr = @[@{kFileName:fileName,kFileData:imgData,kFileMimeType:FILE_MIME_TYPE_FOR_PNG}];
    
    
    // 请求网络
    [myInfoHelper_ updateUserInfoWithBirthDate:birthDate gradUniv:gradUniv educ:educ sign:sign phone:phone filesInfoArr:fileInfoArr completeHandle:^(id result, NSString *errMsg) {
        [SVProgressHUD dismiss];
        if (errMsg) {
            [SVProgressHUD dismiss];
            [LZCHINT title:@"更新失败" type:LZCError duration:2 places:HINT_PLACES callBack:NULL];
        }else {
            [SVProgressHUD dismiss];
            [LZCHINT title:@"更新成功" type:LZCSuccess duration:2 places:HINT_PLACES callBack:NULL];
            [blockSelf_ requestNetData];
            [blockSelf_ savePersonalData:self.userPhotoImage textInfo:nil];
        }
    } uploadProcessingHandler:^(double process) {
        NSLog(@"上传进度:%f",process);
        [SVProgressHUD showProgress:process status:@"更新中..." maskType:SVProgressHUDMaskTypeBlack];
    }];
}

#pragma mark
#pragma mark 保存个人信息至沙盒
- (void)savePersonalData:(UIImage *)userPhotoImg textInfo:(BN_PersonModifyModel *)textInfo {

    // 此处记录生日信息
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:textInfo.babyBirtName forKey:USERDEFAULTS_BIRTHDAYINFO];
    [userDefaults synchronize];

    
    // 保存头像至沙盒
    NSData *data = UIImagePNGRepresentation(userPhotoImg);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:PATH_DOC_USERDATA]) {
        [fileManager createDirectoryAtPath:PATH_DOC_USERDATA withIntermediateDirectories:YES attributes:nil error:nil];
    }
    if (userPhotoImg) {
        [fileManager createFileAtPath:[PATH_DOC_USERDATA stringByAppendingString:@"/userPhoto.png"] contents:data attributes:nil];
    }
    
    /*
     @property (nonatomic, copy) NSString *nickName;
     @property (nonatomic, copy) NSString *biyeSchoolName;
     @property (nonatomic, copy) NSString *xueLiName;
     @property (nonatomic, copy) NSString *telPName;
     @property (nonatomic, copy) NSString *signName;
     @property (nonatomic, copy) NSString *babyBirtName;
     */
    
    // 保存基本信息至沙盒
    if (textInfo) {
        NSDictionary *infoDict = @{@"nickName":textInfo.nickName,@"biyeSchoolName":textInfo.biyeSchoolName,@"xueLiName":textInfo.xueLiName,@"telPName":textInfo.telPName,@"signName":textInfo.signName,@"babyBirtName":textInfo.babyBirtName};
        NSString *filename = [PATH_DOC_USERDATA stringByAppendingPathComponent:@"userData.plist"];
        [infoDict writeToFile:filename atomically:YES];
    }
}

#pragma mark 网络请求数据
- (void)requestNetData {
    __block BN_PersonalInfoModifyViewController *blockSelf_ = self;
    [myInfoHelper_ queryUserInfo:^(id result, NSString *errMsg) {
        if (errMsg) {
            [self cancelHintView];
            [LZCHINT title:errMsg type:LZCError duration:2 places:HINT_PLACES callBack:NULL];
        }else{
            blockSelf_.netDict = (NSDictionary *)result;
            [blockSelf_.modifyTableView reloadData];
            [blockSelf_ initBN_PersonModifyModel:blockSelf_.netDict];
            [self cancelHintView];
        }
    }];
}

- (void)initBN_PersonModifyModel:(NSDictionary *)netDict {
    // 内存
    userInfo = [BN_UserHelper unArchiverAccountInfo];
    self.userType = [userInfo.userType integerValue];
    BN_PersonModifyModel *personModifyModel = [BN_PersonModifyModel sharedModifyModel];
    if (![netDict[@"userName"] isEqual:[NSNull null]]) {
        personModifyModel.nickName = netDict[@"userName"];
    }else {
        personModifyModel.nickName = @"未填写";
    }
    
    NSString *birtDate = netDict[@"birtDate"];
    if (![birtDate isEqual:[NSNull null]] && birtDate) {
        userInfo = [BN_UserHelper unArchiverAccountInfo];
        NSInteger userType = [userInfo.userType intValue];
        switch (userType) {
            case ENUM_ROLE_LEADER:
                personModifyModel.babyBirtName = @"1991-11-11";
                break;
            case ENUM_ROLE_CLASS_TEACHER:
                personModifyModel.babyBirtName = @"1991-11-11";
                break;
            case ENUM_ROLE_PARENT:
                personModifyModel.babyBirtName = netDict[@"birtDate"];
                break;
            default:
                break;
        }
    }else {
        NSString *birthdayStr = FORMAT_STR([[NSUserDefaults standardUserDefaults]objectForKey:USERDEFAULTS_BIRTHDAYINFO]);
        if ([birthdayStr isEqualToString:@"null"]) {
            personModifyModel.babyBirtName = @"2014-07-21";
        }else {
            personModifyModel.babyBirtName = birthdayStr;
        }
    }
    
    if (![netDict[@"gradUniv"] isEqual:[NSNull null]] && netDict[@"gradUniv"]) {
        personModifyModel.biyeSchoolName = netDict[@"gradUniv"];
    }else {
        personModifyModel.biyeSchoolName = @"未填写";
    }
    
    if (![netDict[@"educ"] isEqual:[NSNull null]] && netDict[@"educ"]) {
        personModifyModel.xueLiName = netDict[@"educ"];
    }else {
        personModifyModel.xueLiName = @"未填写";
    }
    
    if (![netDict[@"phon"] isEqual:[NSNull null]] && netDict[@"phon"]) {
        personModifyModel.telPName = netDict[@"phon"];
    }else {
        personModifyModel.telPName = @"未填写";
    }
    
    if (![netDict[@"sign"] isEqual:[NSNull null]] && netDict[@"sign"]) {
        personModifyModel.signName = netDict[@"sign"];
    }else {
        personModifyModel.signName = @"未填写";
    }

    // 本地
    [self savePersonalData:nil textInfo:personModifyModel];
}

#pragma mark 资源

- (void)dealloc
{
    [self releaseResource];
    NSLog(@"个人设置主页释放...");
}
@end
